#ifndef DB_H
#define DB_H

#include "database.h"
#define DB_PASS "root"
#define DB_NAME "chat_system"

// 1.数据库连接管理
// 1.1连接数据库
MYSQL *db_connect()
{
    MYSQL *conn = mysql_init(NULL);
    if (!conn)
    {
        fprintf(stderr, "数据库初始化失败！");
        return NULL;
    }
    if (!mysql_real_connect(conn, DB_HOST, DB_USER, DB_PASS, DB_NAME, 0, NULL, 0))
    {
        fprintf(stderr, "MySQL连接错误：%s\n", mysql_error(conn));
        return NULL;
    }
    return conn;
}

// 1.2关闭数据库连接
void db_close(MYSQL *conn)
{
    if (conn)
    {
        mysql_close(conn);
    }
}

// 2.用户管理
// 2.1注册用户
int db_register_user(MYSQL *conn, const char *username, const char *password)
{
    char query[256];
    snprintf(query, sizeof(query), "INSERT INTO users (username, password) VALUES ('%s', '%s')", username, password);
    if (mysql_query(conn, query))
    {
        fprintf(stderr, "MySQL错误(注册失败):%s\n", mysql_error(conn));
        return 0;
    }
    return 1;
}

// 2.2 用户登录
int db_login_user(MYSQL *conn, const char *username, const char *password)
{
    char query[256];
    snprintf(query, sizeof(query), "SELECT * FROM users WHERE username = '%s' AND password='%s'", username, password);

    if (mysql_query(conn, query))
    {
        fprintf(stderr, "MySQL error: %s\n", mysql_error(conn));
        return 0;
    }
    MYSQL_RES *res = mysql_store_result(conn);
    int num_rows = mysql_num_rows(res);
    mysql_free_result(res);
    return num_rows > 0;
}

// 2.3 删除用户
int db_delete_user(MYSQL *conn, int user_id)
{
    if (!conn)
    {
        return 0;
    }
    const char *query = "DELETE FROM users WHERE id=?";
    MYSQL_STMT *stmt = mysql_stmt_init(conn);
    if (!stmt)
    {
        fprintf(stderr, "MySQL语句初始化失败\n");
        return 0;
    }
    if (mysql_stmt_prepare(stmt, query, strlen(query)))
    {
        fprintf(stderr, "MySQL语句准备错误：%s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return 0;
    }
    MYSQL_BIND bind;
    memset(&bind, 0, sizeof(bind));
    bind.buffer_type = MYSQL_TYPE_LONG;
    bind.buffer = &user_id;
    mysql_stmt_bind_param(stmt, &bind);
    if (mysql_stmt_execute(stmt))
    {
        fprintf(stderr, "MySQL执行错误: %s\n", mysql_stmt_error(stmt));
        mysql_stmt_close(stmt);
        return 0;
    }
    mysql_stmt_close(stmt);
    return 1;
}

// 2.4 修改密码
int db_update_password(MYSQL *conn, int user_id, const char *new_password)
{
    char query[256];
    snprintf(query, sizeof(query), "UPDATE users SET password='%s' WHERE id=%d", new_password, user_id);
    if (mysql_query(conn, query))
    {
        fprintf(stderr, "MySQL error: %s\n", mysql_error(conn));
        return 0;
    }
    return 1;
}

// 3.消息管理
// 3.1存储消息（支持已读/未读）
int db_save_message(MYSQL *conn, int sender_id, int receiver_id, const char *message, int status)
{
    char query[512];
    snprintf(query, sizeof(query), "INSERT INTO messages (sender_id, receiver_id, message, status) VALUES (%d, %d, '%s', %d)", sender_id, receiver_id, message, status);

    if (mysql_query(conn, query))
    {
        fprintf(stderr, "MySQL error: %s\n", mysql_error(conn));
        return 0;
    }
    return 1;
}

// 3.2更新消息状态（已读/未读）
int db_update_message_status(MYSQL *conn, int message_id, int status)
{
    char query[128];
    snprintf(query, sizeof(query), "UPDATE messages SET status=%d WHERE id=%d", status, message_id);

    if (mysql_query(conn, query))
    {
        fprintf(stderr, "MySQL error: %s\n", mysql_error(conn));
        return 0;
    }
    return 1;
}

// 3.3删除消息
int db_delete_message(MYSQL *conn, int message_id)
{
    char query[128];
    snprintf(query, sizeof(query), "DELETE FROM messages WHERE id=%d", message_id);

    if (mysql_query(conn, query))
    {
        fprintf(stderr, "MySQL error: %s\n", mysql_error(conn));
        return 0;
    }
    return 1;
}

// 3.4聊天记录,查询聊天记录，支持分页
void db_fetch_history(MYSQL *conn, int user1_id, int user2_id, int limit)
{
    char query[256];
    snprintf(query, sizeof(query), "SELECT sender_id, receiver_id, message, status FROM messages WHERE (sender_id=%d AND receiver_id=%d) OR (sender_id=%d AND receiver_id=%d) ORDER BY id DESC LIMIT %d", user1_id, user2_id, user2_id, user1_id, limit);

    if (mysql_query(conn, query))
    {
        fprintf(stderr, "MySQL error: %s\n", mysql_error(conn));
        return;
    }

    MYSQL_RES *res = mysql_store_result(conn);
    MYSQL_ROW row;

    while ((row = mysql_fetch_row(res)))
    {
        printf("Sender: %s, Receiver: %s, Message: %s, Status: %s\n", row[0], row[1], row[2], row[3]);
    }

    mysql_free_result(res);
}

#endif
